<template>
	<view class="container">
		<!-- 音乐头部信息 -->
		<view class="music-header">
			<image class="bg-image" src="/static/banner/banner1.jpg" mode="aspectFill"></image>
			<view class="header-content">
				<image class="avatar" src="/static/music/头像.png" mode="aspectFill"></image>
				<view class="info">
					<text class="title">轻音乐精选</text>
					<text class="desc">舒缓的旋律，让您享受购物的每一刻</text>
				</view>
			</view>
		</view>
		
		<!-- 歌词始终在页面最顶端一行，只显示当前高亮歌词 -->
		<view v-if="showLrc && lrcList.length" class="lrc-top-bar">
			<view :style="{ color: lrcColor }">
				{{ lrcList[lrcIndex] ? lrcList[lrcIndex].text : '' }}
			</view>
			
			<view v-if="lrcIndex > 0" :style="{ color: lrcPrevColor }">
				{{ lrcList[lrcIndex + 1].text }}
			</view>
		</view>
		
		<!-- 播放控制器 -->
		<view class="player-control" v-if="currentMusic">
			<view class="music-info">
				<text class="name">{{ currentMusic.name }}</text>
				<text class="artist">{{ currentMusic.artist }}</text>
			</view>
			<!-- 进度条和歌词按钮 -->
			<view class="progress-bar-row">
				<slider 	
					:value="sliderValue"
					@change="onSliderChange"
					@changing="onSliderChanging"
					:show-value="false"
					min="0"
					max="100"
					block-size="16"
					activeColor="#4a66f0"
					backgroundColor="#eee"
					class="progress-slider"
				/>
				<button class="lrc-btn" @click="toggleLrc" v-if="lrcList.length">{{ showLrc ? '歌词' : '歌词' }}</button>
			</view>
			<view class="time-info">
				<text class="current-time">{{ formatTime(currentTime) }}</text>
				<text class="total-time">{{ formatTime(duration) }}</text>
			</view>
			<view class="controls">
				<view class="prev" @click="playPrev">
					<image src="/static/tabbar/左 左.png"></image>
				</view>
				<view class="play-pause" @click="togglePlay">
					<image :src="isPlaying ? '/static/tabbar/暂停.png' : '/static/tabbar/开始.png'"></image>
				</view>
				<view class="next" @click="playNext">
					<image src="/static/tabbar/右 右.png"></image>
				</view>
			</view>
		</view>
		
		<!-- 音乐列表 -->
		<view class="music-list">
			<view class="list-header">
				<text class="title">播放列表</text>
				<text class="count">{{ musicList.length }}首</text>
			</view>
			<view class="list-content">
				<view class="music-item" v-for="(item, index) in musicList" :key="index" @click="playMusic(index)" :class="{active: currentIndex === index}">
					<view class="left">
						<text class="index">{{ index + 1 }}</text>
						<view class="info">
							<text class="name">{{ item.name }}</text>
							<text class="artist">{{ item.artist }}</text>
						</view>
					</view>
					<text class="playing" v-if="currentIndex === index && isPlaying">正在播放</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				musicList: [
					{
						id: 1,
						name: '多幸运',
						artist: '韩安旭',
						src: '/static/music/dxy.mp3'
					},
					{
						id: 2,
						name: '罗生门',
						artist: '梨冻紧,Wiz_H张子豪',
						src: '/static/music/lsm.mp3'
					},
					{
						id: 3,
						name: '慢慢',
						artist: '小乐哥',
						src: '/static/music/mm.mp3'
					},
					{
						id: 4,
						name: '只想说声爱你',
						artist: '白小白',
						src: '/static/music/bxb.m4a'
					},
					{
						id: 5,
						name: 'Baby, Don\'t Cry',
						artist: 'EXO',
						src: '/static/music/Baby.m4a'
					}
				],
				audioContext: null,
				currentIndex: -1,
				isPlaying: false,
				currentMusic: null,
				progress: 0,
				currentTime: 0,
				duration: 0,
				lrc: '',           // 歌词原文
				lrcList: [],       // 歌词解析后数组
				showLrc: false,    // 是否显示歌词
				lrcIndex: 0,       // 当前歌词行
				sliderValue: 0,    // 拖动进度条的值
				isSliderChanging: false // 是否正在拖动进度条
			}
		},
		onLoad() {
			this.initAudio();
		},
		onShow() {
			// 页面显示时检查音乐播放状态
			if (this.audioContext && this.currentMusic && this.isPlaying) {
				this.audioContext.play();
			}
		},
		onHide() {
			// 页面隐藏时暂停播放
			if (this.audioContext && this.isPlaying) {
				this.audioContext.pause();
			}
		},
		onUnload() {
			// 页面卸载时停止播放
			if (this.audioContext) {
				this.audioContext.destroy();
			}
		},
		methods: {
			initAudio() {
				// 初始化音频上下文
				this.audioContext = uni.createInnerAudioContext({
					autoplay: false,
					loop: false,
					obeyMuteSwitch: false
				});
				
				// 监听音频播放结束
				this.audioContext.onEnded(() => {
					console.log('音频播放结束');
					this.playNext();
				});
				
				// 监听音频播放错误
				this.audioContext.onError((res) => {
					console.error('音频播放错误:', res);
					uni.showToast({
						title: '音频播放错误',
						icon: 'none'
					});
					this.isPlaying = false;
				});

				// 监听音频加载状态
				this.audioContext.onCanplay(() => {
					console.log('音频可以播放');
					this.duration = this.audioContext.duration;
				});

				this.audioContext.onWaiting(() => {
					console.log('音频加载中...');
				});
				
				// 监听音频状态变化
				this.audioContext.onPlay(() => {
					console.log('开始播放音频');
					this.isPlaying = true;
				});
				
				this.audioContext.onPause(() => {
					console.log('音频暂停');
					this.isPlaying = false;
				});
				
				this.audioContext.onStop(() => {
					console.log('音频停止');
					this.isPlaying = false;
				});

				// 监听播放进度
				this.audioContext.onTimeUpdate(() => {
					this.currentTime = this.audioContext.currentTime;
					this.duration = this.audioContext.duration;
					this.progress = (this.currentTime / this.duration) * 100;
					if (!this.isSliderChanging) {
						this.sliderValue = this.progress;
					}
					this.updateLrc(this.currentTime);
				});
				
				// 自动播放第一首
				if (this.musicList.length > 0) {
					this.currentMusic = this.musicList[0];
					this.currentIndex = 0;
				}
			},
			playMusic(index) {
				if (index < 0 || index >= this.musicList.length) return;
				
				// 设置当前歌曲
				this.currentIndex = index;
				this.currentMusic = this.musicList[index];
				this.loadLrc(); // 加载歌词
				
				// 显示加载提示
				uni.showLoading({
					title: '加载音频中...'
				});
				
				// 下载音频文件
				uni.downloadFile({
					url: this.currentMusic.src,
					success: (res) => {
						console.log('音频下载成功:', res);
						if (res.statusCode === 200) {
							// 设置音频源并播放
							this.audioContext.src = res.tempFilePath;
							this.audioContext.play();
							this.isPlaying = true;
						} else {
							uni.showToast({
								title: '音频加载失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('音频下载失败:', err);
						uni.showToast({
							title: '音频加载失败',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},
			togglePlay() {
				if (!this.currentMusic) {
					// 如果没有正在播放的歌曲，播放第一首
					if (this.musicList.length > 0) {
						this.playMusic(0);
					}
					return;
				}
				
				if (this.isPlaying) {
					this.audioContext.pause();
				} else {
					this.audioContext.play();
				}
			},
			playPrev() {
				let index = this.currentIndex - 1;
				if (index < 0) {
					index = this.musicList.length - 1;
				}
				this.playMusic(index);
			},
			playNext() {
				let index = this.currentIndex + 1;
				if (index >= this.musicList.length) {
					index = 0;
				}
				this.playMusic(index);
			},
			formatTime(seconds) {
				if (!seconds) return '00:00';
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = Math.floor(seconds % 60);
				return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
			},
			async loadLrc() {
				let lrcPath = '';
				if (this.currentMusic && this.currentMusic.name === '多幸运') {
					lrcPath = '/static/music/多幸运 (1.1x)-韩安旭.lrc';
				} 
					
				else if(this.currentMusic && this.currentMusic.name=='罗生门'){
					lrcPath='/static/music/罗生门2024-Wiz_H张子豪,梨冻紧.lrc'
				}
				else if(this.currentMusic && this.currentMusic.name=='慢慢'){
					lrcPath='static/music/慢慢 小乐哥-Green格林弟.lrc'
				}
				else if(this.currentMusic && this.currentMusic.name=='只想说声爱你'){
					lrcPath='static/music/只想说声爱你 (1.1x DJ 氛围版)-白小白;朱鸽.lrc'
				}
				else if(this.currentMusic && this.currentMusic.name=='Baby, Don\'t Cry'){
					lrcPath='static/music/Baby, Don\'t Cry (人鱼的眼泪)-EXO.lrc'
				}
				else {
					this.lrc = '';
					this.lrcList = [];
					return;
				}
				try {
					const res = await uni.request({ url: lrcPath });
					this.lrc = res.data;
					this.lrcList = this.parseLrc(this.lrc);
				} catch (e) {
					this.lrc = '';
					this.lrcList = [];
				}
			},
			parseLrc(lrc) {
				const lines = lrc.split('\n');
				const result = [];
				const timeReg = /\[(\d{2}):(\d{2}(?:\.\d{1,2})?)\]/;
				for (let line of lines) {
					const match = timeReg.exec(line);
					if (match) {
						const min = parseInt(match[1]);
						const sec = parseFloat(match[2]);
						const text = line.replace(timeReg, '').trim();
						result.push({ time: min * 60 + sec, text });
					}
				}
				return result;
			},
			updateLrc(currentTime) {
				if (!this.lrcList.length) return;
				for (let i = 0; i < this.lrcList.length; i++) {
					if (currentTime < this.lrcList[i].time) {
						this.lrcIndex = i - 1 >= 0 ? i - 1 : 0;
						return;
					}
				}
				this.lrcIndex = this.lrcList.length - 1;
			},
			toggleLrc() {
				this.showLrc = !this.showLrc;
			},
			onSliderChange(e) {
				const value = e.detail.value;
				const seekTime = (value / 100) * this.duration;
				this.audioContext.seek(seekTime);
				this.currentTime = seekTime;
				this.updateLrc(seekTime);
				this.isSliderChanging = false;
			},
			onSliderChanging(e) {
				this.isSliderChanging = true;
				this.sliderValue = e.detail.value;
			}
		},
		computed: {
			lrcColor() {
				if (!this.lrcList.length) return '#888';
				// 当前行显示紫色
				return '#8e24aa';
			},
			lrcPrevColor() {
				if (!this.lrcList.length) return '#888';
				// 其他行显示灰色
				return '#888';
			}
		}
	}
</script>

<style lang="scss">
	.container {
		background-color: #fafafa;
		min-height: 100vh;
	}
	
	.music-header {
		position: relative;
		height: 400rpx;
		overflow: hidden;
		
		.bg-image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			filter: blur(10px);
			transform: scale(1.1);
			z-index: 1;
		}
		
		.header-content {
			position: relative;
			display: flex;
			align-items: center;
			padding: 60rpx 40rpx;
			z-index: 2;
			height: 100%;
			box-sizing: border-box;
			background: rgba(0, 0, 0, 0.3);
			
			.avatar {
				width: 180rpx;
				height: 180rpx;
				border-radius: 90rpx;
				border: 4rpx solid rgba(255, 255, 255, 0.7);
				margin-right: 30rpx;
			}
			
			.info {
				color: #fff;
				
				.title {
					font-size: 36rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
					display: block;
					text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
				}
				
				.desc {
					font-size: 26rpx;
					opacity: 0.9;
					display: block;
					text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
				}
			}
		}
	}
	
	.player-control {
		margin: -60rpx 30rpx 20rpx;
		padding: 30rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;
		z-index: 10;
		
		.music-info {
			text-align: center;
			margin-bottom: 20rpx;
			
			.name {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				display: block;
				margin-bottom: 6rpx;
			}
			
			.artist {
				font-size: 24rpx;
				color: #999;
				display: block;
			}
		}

		.progress-bar-row {
			display: flex;
			align-items: center;
			margin-bottom: 10rpx;
			.progress-slider {
				flex: 1;
			}
			.lrc-btn {
				margin-left: 0rpx;
				font-size: 26rpx;
				padding: 0 20rpx;
				height: 48rpx;
				line-height: 48rpx;
				background: #f0f0f0;
				border-radius: 24rpx;
				color: #4a66f0;
				border: none;
			}
		}

		.time-info {
			display: flex;
			justify-content: space-between;
			font-size: 24rpx;
			color: #999;
			margin-bottom: 20rpx;
		}
		
		.controls {
			display: flex;
			justify-content: center;
			align-items: center;
			
			.prev, .next {
				width: 80rpx;
				height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				
				image {
					width: 40rpx;
					height: 40rpx;
				}
			}
			
			.play-pause {
				width: 100rpx;
				height: 100rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 50%;
				margin: 0 30rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				
				image {
					width: 50rpx;
					height: 50rpx;
				}
			}
		}
	}
	
	.music-list {
		margin: 20rpx 30rpx;
		padding: 20rpx 30rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		
		.list-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f0f0f0;
			margin-bottom: 10rpx;
			
			.title {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
			}
			
			.count {
				font-size: 24rpx;
				color: #999;
			}
		}
		
		.list-content {
			.music-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #f8f8f8;
				
				&.active {
					background: rgba(74, 102, 240, 0.05);
				}
				
				.left {
					display: flex;
					align-items: center;
					
					.index {
						width: 60rpx;
						font-size: 28rpx;
						color: #999;
						text-align: center;
					}
					
					.info {
						margin-left: 10rpx;
						
						.name {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 4rpx;
							display: block;
						}
						
						.artist {
							font-size: 22rpx;
							color: #999;
							display: block;
						}
					}
				}
				
				.playing {
					font-size: 24rpx;
					color: #4a66f0;
					padding: 4rpx 16rpx;
					border-radius: 20rpx;
					background: rgba(74, 102, 240, 0.1);
				}
			}
		}
	}
	
	@font-face {
		font-family: "iconfont";
		
		}

	.iconfont {
		font-family: "iconfont" !important;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	.lrc-top-bar {
		position: fixed;
		left: 0;
		right: 0;
		top: 65%;
		z-index: 1000;
		background: transparent;
		padding: 0;
		margin: 0;
		text-align: center;
		font-size: 28rpx;
		line-height: 2.2;
		color: #888;
		transition: color 0.3s;
		font-weight: bold;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
		
		// &.active, &.lrc-top-bar-active {
		// 	color: #8e24aa;
		// }
	}
</style> 